package com.itboye.system.filter;

import com.itboye.config.GlobalConfig;
import com.itboye.system.exception.ByBaseException;
import com.itboye.system.exception.ByExceptionCode;
import com.itboye.system.helper.ByConsoleHelper;
import com.itboye.api.model.ByResponseData;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import static com.itboye.api.model.ByResponseData.fail;

/**
 * 获取api请求数据模型过滤器
 * Created by hebidu on 16/5/11.
 */
@WebFilter(filterName = "ApiRequestDataFilter")
public class ApiRequestDataFilter implements Filter {


    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws  ServletException, IOException {

        //将请求的数据解密
        String itboyeDes = req.getParameter("itboye");
//        String notifyId = req.getParameter("notify_id");
        String clientId = req.getParameter("client_id");


        try {
//            if (notifyId == null ||  notifyId.length() == 0) {
//                resp.setCharacterEncoding("utf-8");
//                resp.setContentType("application/json;");
//
//                ByResponseData data = fail(ByExceptionCode.Lack_Parameter, "缺少notifyId参数", GlobalConfig.DEFAULT_CLIENT_SECRET,GlobalConfig.DEFAULT_NOTIFY_ID);
//                data.setClientId(GlobalConfig.DEFAULT_CLIENT_ID);
//                resp.getWriter().println(data.toJson());
//                return;
//            }

            if (clientId == null || clientId.length() == 0) {
                resp.setCharacterEncoding("utf-8");
                resp.setContentType("application/json;");

                ByResponseData data = fail(ByExceptionCode.Lack_Parameter, "缺少clientId参数", GlobalConfig.DEFAULT_CLIENT_SECRET,GlobalConfig.DEFAULT_NOTIFY_ID);
                data.setClientId(GlobalConfig.DEFAULT_CLIENT_ID);
                resp.getWriter().println(data.toJson());
                return;
            }


            //缺少itboye参数的处理,所以必须传入该参数
            if (itboyeDes == null || itboyeDes.length() == 0) {
                resp.setCharacterEncoding("utf-8");
                resp.setContentType("application/json;");

                ByResponseData data = fail(ByExceptionCode.Lack_Parameter, "缺少itboye参数", GlobalConfig.DEFAULT_CLIENT_SECRET,GlobalConfig.DEFAULT_NOTIFY_ID);
                data.setClientId(GlobalConfig.DEFAULT_CLIENT_ID);
                resp.getWriter().println(data.toJson());
                return;
            }
        }
        catch (ByBaseException e) {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }

        chain.doFilter(req, resp);

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
